package unv.esiag.uchiha;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;

import unv.esiag.uchiha.core.Participant;
import unv.esiag.uchiha.topics.STopic;

public class ClientPanel extends JPanel implements ActionListener{
	private static final long serialVersionUID = 1L;
	private JTextField field;
	private TreePanel tree;
	private Participant participant;
	public ClientPanel(TreePanel tree) {
		this.tree = tree;
		setLayout(new FlowLayout());
		field = new JTextField(10);
		JButton butt1 = new JButton("Init");
		butt1.addActionListener(this);
		JButton butt2 = new JButton("Create Topic");
		butt2.addActionListener(this);
		JButton butt3 = new JButton("Modifie Cache");
		butt3.addActionListener(this);
		add(field);
		add(butt1);
		add(butt2);
		add(butt3);
	}
	public void actionPerformed(ActionEvent e) {
		JButton butt = (JButton)e.getSource();
		if(butt.getText().equals("Init")){
			STopic topic = tree.getSelectedTopic();
			if(topic != null){
				String fullName = topic.getFullName();
				if(fullName.equals("Rooot")){
					fullName = "";
				}
				participant = new Participant(fullName);
				try{
					participant.addListener(tree);
					participant.init();
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		}else if(butt.getText().equals("Create Topic")){
			if(participant != null){
				try{
					participant.createTopic(field.getText());
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		}else if(butt.getText().equals("Modifie Cache")){
			if(participant != null){
				try{
					participant.write(field.getText());
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		}
	}
}
